package com.pengli.mytools.ui.mainPage.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.pengli.citypicker.CityPicker;
import com.pengli.citypicker.adapter.OnPickListener;
import com.pengli.citypicker.model.City;
import com.pengli.citypicker.model.HotCity;
import com.pengli.citypicker.model.LocatedCity;
import com.pengli.mytools.MyApplication;
import com.pengli.mytools.R;
import com.pengli.mytools.beans.po.Cities;
import com.pengli.mytools.greendao.CitiesDao;
import com.pengli.mytools.greendao.DaoSession;
import com.permissionx.guolindev.PermissionX;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeFragment extends Fragment {

    @BindView(R.id.city_picker)
    TextView city_picker;
    private ArrayList<HotCity> hotCities = new ArrayList<>();
    private AMapLocationClient mLocationClient;
    private Context context;
    private LocatedCity locatedCity = null;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        ButterKnife.bind(this, root);
        context = getActivity();

        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));

        //动态获取定位权限
        PermissionX.init(HomeFragment.this)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE)
                .explainReasonBeforeRequest()
                .onExplainRequestReason((scope, deniedList, beforeRequest) -> {
//                    CustomDialog customDialog = new CustomDialog(MainJavaActivity.this, "PermissionX needs following permissions to continue", deniedList);
//                    scope.showRequestReasonDialog(customDialog);
                    scope.showRequestReasonDialog(deniedList, "PermissionX needs following permissions to continue", "Allow");
                })
                .onForwardToSettings((scope, deniedList) -> {
                    scope.showForwardToSettingsDialog(deniedList, "Please allow following permissions in settings", "Allow");
                })
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        Toast.makeText(context, "成功获取定位权限", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(context, "定位权限被拒绝: $deniedList", Toast.LENGTH_LONG).show();
                    }
                });


        setLocation();
        init();


        return root;
    }

    private void setLocation() {
        try {
            //隐私政策合规
            AMapLocationClient.updatePrivacyShow(context, true, true);
            AMapLocationClient.updatePrivacyAgree(context, true);
            //初始化定位
            mLocationClient = new AMapLocationClient(context);
            if (null != mLocationClient) {
                //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
                AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
                mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
                mLocationClient.setLocationOption(mLocationOption);
                //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                mLocationClient.stopLocation();
                mLocationClient.startLocation();

                //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
//              mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
                //设置定位模式为AMapLocationMode.Device_Sensors，仅设备模式。
//              mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
                //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
                mLocationOption.setHttpTimeOut(30000);
                //给定位客户端对象设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
                //启动定位
                mLocationClient.startLocation();

                //设置定位回调监听
                mLocationClient.setLocationListener(amapLocation -> {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            // 解析amapLocation获取相应内容。
//                            amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                            amapLocation.getLatitude();//获取纬度
//                            amapLocation.getLongitude();//获取经度
//                            amapLocation.getAccuracy();//获取精度信息
//                            amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                            amapLocation.getCountry();//国家信息
                            String province = amapLocation.getProvince();//省信息
                            String city = amapLocation.getCity();//城市信息

                            Toast.makeText(
                                    getContext(),
                                    String.format("定位：%s，%s", province,city),
                                    Toast.LENGTH_SHORT)
                                    .show();
//                            amapLocation.getDistrict();//城区信息
//                            amapLocation.getStreet();//街道信息
//                            amapLocation.getStreetNum();//街道门牌号信息
//                            amapLocation.getCityCode();//城市编码
//                            amapLocation.getAdCode();//地区编码
//                            amapLocation.getAoiName();//获取当前定位点的AOI信息
//                            amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                            amapLocation.getFloor();//获取当前室内定位的楼层
//                            amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
                            //获取定位时间
//                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                            Date date = new Date(amapLocation.getTime());
//                            df.format(date);

                            DaoSession daoSession = MyApplication.getInstance().getDaoSession();
                            CitiesDao chinaCitiesV2Dao = daoSession.getCitiesDao();
                            List<Cities> list = chinaCitiesV2Dao.queryBuilder().build().list();
                            Cities citiesV2 = null;
                            for (int i = 0; i < list.size(); i++) {
                                Cities cities = list.get(i);
                                if (province.contains(cities.getC_province()) && city.contains(cities.getC_name())) {
                                    citiesV2 = cities;
                                    break;
                                }
                            }
                            if (citiesV2 != null) {
                                locatedCity = new LocatedCity(citiesV2.getC_name(), citiesV2.getC_province(), citiesV2.getC_code());
                                city_picker.setText(citiesV2.getC_name());
                            }


                        } else {
                            //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                            Log.e("AmapError", "location Error, ErrCode:"
                                    + amapLocation.getErrorCode() + ", errInfo:"
                                    + amapLocation.getErrorInfo());
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void init() {
        city_picker.setOnClickListener(v -> {
            CityPicker.from(getActivity())
                    .enableAnimation(false)
                    .setAnimationStyle(R.style.CustomAnim)
                    .setLocatedCity(locatedCity)
                    .setHotCities(hotCities)
                    .setOnPickListener(new OnPickListener() {
                        @Override
                        public void onPick(int position, City data) {
//                            city_picker.setText(String.format("当前城市：%s，%s", data.getName(), data.getCode()));
                            city_picker.setText(data.getName());

                            Toast.makeText(
                                    getContext(),
                                    String.format("点击的数据：%s，%s", data.getName(), data.getCode()),
                                    Toast.LENGTH_SHORT)
                                    .show();
                        }

                        @Override
                        public void onCancel() {
                            Toast.makeText(getContext(), "取消选择", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onLocate() {
//                            //开始定位，这里模拟一下定位
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    CityPicker.from(getActivity()).locateComplete(new LocatedCity("深圳(模拟)", "广东", "101280601"), LocateState.SUCCESS);
//                                }
//                            }, 2000);
                        }
                    })
                    .show();
        });
    }

    @OnClick({R.id.home_movie, R.id.home_music, R.id.home_doc})
    public void onClick(View view) {
        String type = null;
        switch (view.getId()) {
            case R.id.home_movie:
                type = "movie";
                break;
            case R.id.home_music:
                type = "music";
                break;
            case R.id.home_doc:
                type = "doc";
                break;
        }
        Intent intent1 = new Intent(getActivity(), HomeDetailActivity.class);
        intent1.putExtra("type", type);
        startActivity(intent1);

    }

}